{% extends 'carry/layout.html' %}
{% block css %}
        <link href="/static/plugins/dropzone/dropzone.css" rel="stylesheet">
        <script src="/static/plugins/dropzone/dropzone.js"></script>
{% endblock %}


{% block content%}
    <div id="page-title">
        <h1 class="page-header text-overflow">主机列表</h1>

        <!--Searchbox-->
        <div class="searchbox">
            <div class="input-group custom-search-form">
                <input type="text" class="form-control" placeholder="Search..">
                <span class="input-group-btn">
                    <button class="text-muted" type="button"><i class="pli-magnifi-glass"></i></button>
                </span>
            </div>
        </div>
    </div>
    <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
    <!--End page title-->
        <!--Breadcrumb-->
    <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
    <ol class="breadcrumb">
        <li><a href="#">Home</a></li>
        <li><a href="#">Library</a></li>
        <li class="active">主机列表</li>
    </ol>
    <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
    <!--End breadcrumb-->
    <div id="page-content">
                <div class="panel col-lg-3">
            <div class="panel-heading">
                <h3 class="panel-title">主机组 <span id="selected_hosts"></span></h3>
            </div>
            <div class="panel-body">

                <ul class="list-group" id="host_groups">
                {% for group in account_obj.host_groups.all %}

                    <li class="list-group-item " ><span class="badge badge-success">{{ group.host_user_binds.count }}</span>
                        <input type="checkbox" onclick="CheckAll(this)">
                        <a onclick="DisplayHostList(this)">{{ group.name }}</a>


                        <ul class="hide checkbox">
                            {% for bind_host in group.host_user_binds.all %}
                                <li><input onclick="ShowCheckedHostCount()" type="checkbox" value="{{ bind_host.id }}">{{ bind_host.host.ip_addr }}</li>
                            {% endfor %}
                        </ul>
                    </li>

                {% endfor %}
                    <li class="list-group-item " > <span class="badge badge-success">{{ account_obj.host_user_binds.count }}</span>
                       <input type="checkbox" onclick="CheckAll(this)">
                        <a onclick="DisplayHostList(this)">未分组主机</a>
                        <ul class="hide checkbox">
                            {% for bind_host in account_obj.host_user_binds.all %}
                                <li><input onclick="ShowCheckedHostCount()" type="checkbox" value="{{ bind_host.id }}">{{ bind_host.host.ip_addr }}</li>
                            {% endfor %}
                        </ul>
                    </li>

                </ul>



            </div>
        </div>

        <div class="col-lg-9">
            <div class="panel">
                <div class="panel-heading">
                    <h3 class="panel-title">文件传输</h3>
                </div>
                <div class="panel-body">
                    <select name="transfer-type" onchange="ToggleUploadEle(this)">
                        <option value="send">发送文件到远程主机</option>
                        <option value="get">from远程主机下载文件</option>
                    </select>
                    <form id="filedropzone" action="{% url 'task_file_upload' %}?random_str={{ random_str }}" class="dropzone dz-clickable">
                        <div class="dz-default dz-message">
                            <div class="dz-icon">
                                <i class="demo-pli-upload-to-cloud icon-5x"></i>
                            </div>
                            <div>
                                <span class="dz-text">Drop files to upload</span>
                                <p class="text-sm text-muted">or click to pick manually</p>
                            </div>
                        </div>

                    </form>
{#                    <input type="hidden" value="{{ random_str }}" name="random_str">#}
                    <input id="remote_path" class="form-control" type="text" placeholder="远程路径">

                    <button onclick="PostTask('file_transfer')" class="btn btn-info pull-right">执行</button>
                    <button  class="btn btn-danger ">终止</button>
                    <a id="file-download-btn" class="btn btn-info hide" href="" >下载任务文件到本地</a>


                </div>
            </div>
            <div id="task_result_panel"  class="panel">
                <div class="panel-heading">
                    <h3 class="panel-title">任务结果</h3>
                </div>
                <div class="panel-body">
                    <div  class="progress">
                        <div id='task_progress' style="width: 0%;" class="progress-bar progress-bar-info"></div>
                    </div>
                    <div id="task_result"></div>
                </div>
            </div>
        </div>

        </div>
    </div>

<script>
    function  DisplayHostList(self) {
        $(self).next().toggleClass("hide");
    }

    function CheckAll(self){
        console.log($(self).prop('checked'))
        $(self).parent().find("ul :checkbox").prop('checked',$(self).prop('checked'))

        ShowCheckedHostCount()
    }

    function ShowCheckedHostCount(){
        var selected_host_count = $("#host_groups ul").find(":checked").length
        console.log(selected_host_count)
        $("#selected_hosts").text(selected_host_count);
        return selected_host_count
    }


    function GetTaskResult(task_id,task_timeout) {
        $.getJSON("{% url 'get_task_result' %}",{'task_id':task_id},function(callback){

            console.log(callback)

            var result_ele = ''
            var all_task_finished = true
            var finished_task_count = 0 ;
            $.each(callback,function (index,i) {
                var p_ele = "<p>" + i.host_user_bind__host__hostname + "(" +i.host_user_bind__host__ip_addr +") ------" +
                    i.status + "</p>"
                var res_ele = "<pre>" + i.result +"</pre>"

                var single_result = p_ele + res_ele
                result_ele += single_result

                //check if ths sub task is finished.
                if ( i.status == 3){
                    all_task_finished = false;
                }else {
                    //task not finished yet
                    finished_task_count += 1;
                }

            });//end each
            //check if the task_timer_count < task_timeout, otherwise it means the task is timedout, setInterval function need to be cancelled
            if (task_timeout_counter < task_timeout){
                // not timed out yet
                task_timeout_counter += 2;

            }else {
                all_task_finished = true; // set all task to be finished ,because it 's already reached the global timeout

                $.niftyNoty({
                    type: 'danger',
                    container : '#task_result_panel',
                    html : '<h4 class="alert-title">Task timed out!</h4><p class="alert-message">The task has timed out!</p><div class="mar-top"><button type="button" class="btn btn-info" data-dismiss="noty">Close this notification</button></div>',
                    closeBtn : false
                });
            }

            if ( all_task_finished){
                clearInterval(result_timer);
                console.log("timmer canceled....")
            }


            $("#task_result").html(result_ele)
            // set progress bar
            var total_finished_percent = parseInt(finished_task_count / callback.length * 100 );
            $("#task_progress").text(total_finished_percent+"%");
            $("#task_progress").css("width",total_finished_percent +"%");
        });//end getJSON

    }


    function  PostTask(task_type) {
        //1. 验证主机列表已选，命令已输入
        //2. 提交任务到后台
        var selected_host_ids = [];
        var selected_host_eles = $("#host_groups ul").find(":checked")
        $.each(selected_host_eles,function (index,ele) {
            selected_host_ids.push($(ele).val())
        })
        console.log(selected_host_ids)
        if ( selected_host_ids.length == 0){
            alert("主机未选择!")
            return false
        }

        if ( task_type == 'cmd'){
            var cmd_text = $.trim($("#cmd").val())
            if ( cmd_text.length == 0){
                alert("未输入命令!")
                return false

            }
        }else {
            //file_transfer
            var remote_path = $("#remote_path").val()
            if ($.trim(remote_path).length == 0){
                alert("must specify remote path ")
                return false
            }
        }



        var task_data = {
            'task_type':task_type,
            'selected_host_ids': selected_host_ids,
            //'cmd': cmd_text
        }
        if ( task_type == 'cmd'){
            task_data['cmd'] =  cmd_text
        }else {
            var file_transfer_type = $("select[name='transfer-type']").val()
            task_data['file_transfer_type'] = file_transfer_type
            task_data['random_str'] = "{{ random_str }}"
            task_data['remote_path'] = $("#remote_path").val()


        }


        $.post("{% url 'multitask' %}",{'csrfmiddlewaretoken':"{{ csrf_token }}",'task_data':JSON.stringify(task_data)},
            function(callback){
                    console.log(callback) ;// task id
                    var callback = JSON.parse(callback)

                    GetTaskResult(callback.task_id,callback.timeout)
                    task_timeout_counter = 0 // add 2 during each call of GetTaskResult
                    result_timer = setInterval(function () {
                        GetTaskResult(callback.task_id,callback.timeout)
                    },2000)

                    //diplay download file btn
                    $("#file-download-btn").removeClass("hide").attr('href', "{% url 'task_file_download' %}?task_id="+callback.task_id);


            } );//end post

    }
</script>
<script>

    $(document).ready(function () {

        //Dropzone.autoDiscover = false;
        //var myDropzone = new Dropzone("#filedropzone");
        Dropzone.options.filedropzone  = {
              paramName: "file", // The name that will be used to transfer the file
              maxFilesize: 2, // MB
              maxFiles:2,
              accept: function(file, done) {
                if (file.name == "test.jpg") {
                  done("Naha, you don't.");
                }
                else { done(); }
              }
        };
        console.log('ddddd')


{#       myDropzone = new Dropzone("#filedropzone");#}
{#       myDropzone.on("addedfile", function(file) {#}
{#        /* Maybe display some more file information on your page */#}
{#         console.log(file)#}
{#       });#}


    });//end doc ready


    function  ToggleUploadEle(self) {

        console.log($(self).val())
        if ( $(self).val() == 'get'){
            $(self).next().addClass("hide")
        }else {
            $(self).next().removeClass('hide')
        }

    }

</script>

{% endblock %}